package com.jarvis.pzz.modules.shop.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.GroundOverlayOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jarvis.pzz.R;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.ShopsListModel;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.Util;
import com.jarvis.pzz.util.ViewHolderUtil;
import com.jarvis.pzz.util.net.RequestApi;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MapActivity extends Activity implements OnGetGeoCoderResultListener, View.OnClickListener, OnGetPoiSearchResultListener {
    GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    BaiduMap mBaiduMap = null;
    MapView mMapView = null;
    private InfoWindow mInfoWindow;
    private LinearLayout lin_school;
    private LinearLayout lin_market;
    private LinearLayout lin_supermarket;
    private LinearLayout lin_office;

    private ImageView img_school;
    private ImageView img_market;
    private ImageView img_supmarket;
    private ImageView img_office;
    private TextView tv_school;
    private TextView tv_market;
    private TextView tv_supmarket;
    private TextView tv_office;

    private PoiSearch mPoiSearch = null;
    private int loadIndex = 0;
    private int searchType;  //0:学校 1：商场 2：超市 3：写字楼
    PoiNearbySearchOption nearbySearchOption;

    LatLng ptCenter;
    LatLng myPt;
    int radius = 2000;

    private Marker myMarker;

    private String shopAddress;
    private String area;
    List<Overlay> mOverlayList = new ArrayList<>();
    List<OverlayOptions> overlayOption = new ArrayList<>();
    List<PoiInfo> allPoi=new ArrayList<>();

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        initView();
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        String shopLocation = getIntent().getStringExtra("shopLocation");
        shopAddress = getIntent().getStringExtra("shopAddress");
        area = getIntent().getStringExtra("area");
        String[] split = shopLocation.split(",");
        ptCenter = new LatLng(Float.parseFloat(split[0]), Float.parseFloat(split[1]));
        // 反Geo搜索
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(ptCenter));

        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("wgs84"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            //系统版本大于19
            setTranslucentStatus(true);
        }
        setStatusWhite(true);
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        lin_school = (LinearLayout) findViewById(R.id.lin_school);
        lin_market = (LinearLayout) findViewById(R.id.lin_market);
        lin_supermarket = (LinearLayout) findViewById(R.id.lin_supermarket);
        lin_office = (LinearLayout) findViewById(R.id.lin_office);
        img_school = (ImageView) findViewById(R.id.img_school);
        img_market = (ImageView) findViewById(R.id.img_market);
        img_supmarket = (ImageView) findViewById(R.id.img_supmarket);
        img_office = (ImageView) findViewById(R.id.img_office);
        tv_school = (TextView) findViewById(R.id.tv_school);
        tv_market = (TextView) findViewById(R.id.tv_market);
        tv_supmarket = (TextView) findViewById(R.id.tv_supmarket);
        tv_office = (TextView) findViewById(R.id.tv_office);
        findViewById(R.id.rel_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBaiduMap = mMapView.getMap();
        lin_school.setOnClickListener(this);
        lin_market.setOnClickListener(this);
        lin_supermarket.setOnClickListener(this);
        lin_office.setOnClickListener(this);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                mBaiduMap.hideInfoWindow();
                if (myMarker == marker) {
                    View view = LayoutInflater.from(MapActivity.this).inflate(R.layout.item_map, null);
                    TextView tv_name = ViewHolderUtil.find(view, R.id.tv_name);
                    TextView tv_value = ViewHolderUtil.find(view, R.id.tv_value);
                    tv_name.setText(shopAddress);
                    tv_value.setText(area);
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(view, ll, -60);
                    mBaiduMap.showInfoWindow(mInfoWindow);
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 构建 导航参数
                            NaviParaOption para = new NaviParaOption()
                                    .startPoint(myPt).endPoint(ptCenter);

                            try {
                                BaiduMapNavigation.openBaiduMapNavi(para, MapActivity.this);
                            } catch (BaiduMapAppNotSupportNaviException e) {
                                e.printStackTrace();
                                showDialog();
                            }

                        }
                    });
                } else {
                    if (!mOverlayList.contains(marker)) {
                        return false;
                    }
                    PoiInfo poi = allPoi.get(marker.getExtraInfo().getInt("index"));
                    // if (poi.hasCaterDetails) {
                    mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                            .poiUid(poi.uid));
                }
                return true;
            }

        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

    }

    public void setStatusWhite(boolean status) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            //系统版本大于19
            setTranslucentStatus(true);
        }

        Class clazz = getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            if (status) {
                extraFlagField.invoke(getWindow(), darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
            } else {
                extraFlagField.invoke(getWindow(), 0, darkModeFlag);//清除黑色字体
            }
        } catch (Exception e) {

        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 提示未安装百度地图app或app版本过低
     */
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                OpenClientUtil.getLatestBaiduMapApp(MapActivity.this);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();

    }

    //0:学校 1：商场 2：超市 3：写字楼
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lin_school:
                searchType = 0;
                showData(tv_school);
                nearbySearchOption = new PoiNearbySearchOption().keyword("学校").sortType(PoiSortType.distance_from_near_to_far).location(ptCenter)
                        .radius(radius).pageNum(loadIndex).pageCapacity(10).sortType(PoiSortType.comprehensive);
                mPoiSearch.searchNearby(nearbySearchOption);
                break;
            case R.id.lin_market:
                searchType = 1;
                showData(tv_market);
                nearbySearchOption = new PoiNearbySearchOption().keyword("商场").sortType(PoiSortType.distance_from_near_to_far).location(ptCenter)
                        .radius(radius).pageNum(loadIndex).pageCapacity(10).sortType(PoiSortType.comprehensive);
                mPoiSearch.searchNearby(nearbySearchOption);
                break;
            case R.id.lin_supermarket:
                searchType = 2;
                showData(tv_supmarket);
                nearbySearchOption = new PoiNearbySearchOption().keyword("超市").sortType(PoiSortType.distance_from_near_to_far).location(ptCenter)
                        .radius(radius).pageNum(loadIndex).pageCapacity(10).sortType(PoiSortType.comprehensive);
                mPoiSearch.searchNearby(nearbySearchOption);
                break;
            case R.id.lin_office:
                searchType = 3;
                showData(tv_office);
                nearbySearchOption = new PoiNearbySearchOption().keyword("写字楼").sortType(PoiSortType.distance_from_near_to_far).location(ptCenter)
                        .radius(radius).pageNum(loadIndex).pageCapacity(10).sortType(PoiSortType.comprehensive);
                mPoiSearch.searchNearby(nearbySearchOption);
                break;
        }
    }

    private void showData(TextView tv) {
        img_school.setImageResource(R.drawable.map_school);
        img_supmarket.setImageResource(R.drawable.map_supermarket);
        img_office.setImageResource(R.drawable.map_office);
        img_market.setImageResource(R.drawable.map_market);
        tv_school.setTextColor(getResources().getColor(R.color.grey));
        tv_market.setTextColor(getResources().getColor(R.color.grey));
        tv_supmarket.setTextColor(getResources().getColor(R.color.grey));
        tv_office.setTextColor(getResources().getColor(R.color.grey));
        if (searchType == 0) {
            img_school.setImageResource(R.drawable.img_school_press);
        } else if (searchType == 1) {
            img_market.setImageResource(R.drawable.img_market_press);
        } else if (searchType == 2) {
            img_supmarket.setImageResource(R.drawable.img_supermarket_press);
        } else if (searchType == 3) {
            img_office.setImageResource(R.drawable.img_office_press);
        }
        tv.setTextColor(getResources().getColor(R.color.purple));
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        MobclickAgent.onResume(this);
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        mSearch.destroy();
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        super.onDestroy();
    }


    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        myMarker = (Marker) mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.banner_dot_select)));
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(result
                .getLocation(), 17);
        mBaiduMap.setMapStatus(mapStatusUpdate);

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Map Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(MapActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();

            BitmapDescriptor centerBitmap = null;
            if (searchType == 0) {
                centerBitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.img_school_potision);
            } else if (searchType == 1) {
                centerBitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.img_rmarket_position);
            } else if (searchType == 2) {
                centerBitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.img_supemarket_potision);
            } else if (searchType == 3) {
                centerBitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.img_office_position);
            }
            allPoi = result.getAllPoi();
            overlayOption = getOverlayOptions(result, centerBitmap);
            addToMap();
            mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(ptCenter));
            return;
        }
    }

    public final List<OverlayOptions> getOverlayOptions(PoiResult mPoiResult, BitmapDescriptor centerBitmap) {
        if (mPoiResult == null || mPoiResult.getAllPoi() == null) {
            return null;
        }
        List<OverlayOptions> markerList = new ArrayList<OverlayOptions>();
        int markerSize = 0;
        for (int i = 0; i < mPoiResult.getAllPoi().size(); i++) {
            if (mPoiResult.getAllPoi().get(i).location == null) {
                continue;
            }
            markerSize++;
            Bundle bundle = new Bundle();
            bundle.putInt("index", i);
            markerList.add(new MarkerOptions()
                    .icon(centerBitmap).extraInfo(bundle)
                    .position(mPoiResult.getAllPoi().get(i).location))
            ;

        }
        return markerList;
    }

    /**
     * 将所有Overlay 添加到地图上
     */
    public void addToMap() {
        if (mBaiduMap == null) {
            return;
        }
        for (OverlayOptions option : overlayOption) {
            mOverlayList.add(mBaiduMap.addOverlay(option));
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(MapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
//            Toast.makeText(MapActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
//                    .show();
            View view = LayoutInflater.from(MapActivity.this).inflate(R.layout.item_search_result, null);
            TextView tv_name = ViewHolderUtil.find(view, R.id.tv_name);
            TextView tv_value = ViewHolderUtil.find(view, R.id.tv_value);
            tv_name.setText(result.getName());
            tv_value.setText(result.getAddress());
            LatLng ll = result.getLocation();
            mInfoWindow = new InfoWindow(view, ll, -60);
            mBaiduMap.showInfoWindow(mInfoWindow);
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            myPt = new LatLng(location.getLatitude(), location.getLongitude());
//            Toast.makeText(MapActivity.this, "city:" + location.getCity()+ "  District:" + location.getDistrict()+"  latitude:" + location.getLatitude()
//                    + " longitude:" + location.getLongitude() + "---", Toast.LENGTH_LONG)
//                    .show();
            if (mLocClient.isStarted()) {
                // 获得位置之后停止定位
                mLocClient.stop();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
}
